<?php 
namespace app\system\admin;
use app\system\admin\Admin;
use think\Db;
use app\system\model\Orders as OrdersModel;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use lib\Refund_pub;
/**
 *  @author Lin
 *  @time 2021/7/22
 */
class Orders extends Admin
{
    protected function initialize()
    {
        parent::initialize();
        set_time_limit(0);
        
    }

    function index(){
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $keyword = input('keyword');
            if($keyword){
                $where[] = ['a.orders_id|a.name|b.nickname','like',"%".$keyword."%"];
                // $where[] = ['name','like',"%".$keyword."%"];
            }
            $orders = 'a.is_send asc,a.ctime desc';
            $status = input('status');
            if($status){
                // 待支付
                if($status==1){
                    $where[] = ['a.pay_status','eq',0];
                }
                // 待发货
                elseif($status==2){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_send','eq',0];
                    $where[] = ['a.sure_return','neq',1];
                }
                // 待收货
                elseif($status==3){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_send','eq',1];
                    $where[] = ['a.is_que','eq',0];
                    $where[] = ['a.sure_return','neq',1];
                }
                // 退换货
                elseif($status==5){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_refund','eq',1];
                    $orders = 'a.refund_status asc,refund_time desc';
                }
                // 已完成
                elseif($status==4){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_send','eq',1];
                    $where[] = ['a.is_que','eq',1];
                    $where[] = ['a.sure_return','neq',1];
                }
                // 积分商城订单
                elseif($status==6){
                    $where[] = ['a.type','eq',1];
                } 
                // 申请开票订单
                elseif($status==7){
                    $where[] = ['a.fp_title','neq',''];
                    $where[] = ['a.taxNumber','neq',''];
                    $where[] = ['a.is_piao','eq',0];
                } 
                // 已开票订单
                elseif($status==8){
                    $where[] = ['a.is_piao','eq',1];
                } 
            }
            
            $list = Db::name('orders')->alias('a')->join('user b','a.uid=b.id','left')->where($where)->page($page)->limit($limit)->order($orders)->field('a.*,b.nickname')->select();

            if($list){
                foreach($list as $key=>&$value){
                    $goods_id_arr = explode(',',$value['goods_id']);
                    $goods_spec_arr = explode(',',$value['goods_spec']);
                    $goods_price_arr = explode(',',$value['goods_price']);
                    $goods_num_arr = explode(',',$value['goods_num']);
                    $i = 0;
                    $goods_name = array();
                    foreach($goods_id_arr as $k=>&$v){
                        $ginfo = Db::name('product')->where('id',$v)->field('name,share_img')->find();
                        $goods_info[$i] = array(
                            'id'=>$v,
                            'goods_spec'=>$goods_spec_arr[$k],
                            'goods_num'=>$goods_num_arr[$k],
                            'goods_price'=>$goods_price_arr[$k],
                            'goods_name'=>$ginfo['name'],
                            'goods_img'=>$ginfo['share_img']
                        );
                        $goods_name[$i] = $ginfo['name'];
                        $i++;
                    }
                    $value['output_goods_name'] = implode(',',$goods_name);
                    $value['goods_info'] = $goods_info;

                    $value['ctime'] = $value['ctime']?date('Y-m-d H:i:s',$value['ctime']):'';
                    $value['pay_time'] = $value['pay_time']?date('Y-m-d H:i:s',$value['pay_time']):'';

                    if($value['quan_id']>0){
                        $quan_id = Db::name('user_quan')->where('id',$value['quan_id'])->value('quan_id');
                        $quan_name = Db::name('product_quan')->where('id',$quan_id)->value('quan_name');
                        $value['quan_name'] = $quan_name?$quan_name:'';
                        $value['quan_price'] = $value['quan_price']?$value['quan_price']:0;
                    }

                    if($value['pay_status']==0){
                        $value['status'] = '待支付';
                    }
                    elseif($value['pay_status']==1&&$value['is_send']==0){
                        $value['status'] = '待发货';
                    }
                    elseif($value['pay_status']==1&&$value['is_send']==1&&$value['is_que']==0){
                        $value['status'] = '待收货';
                    }
                    elseif($value['pay_status']==1&&$value['is_send']==1&&$value['is_que']==1){
                        $value['status'] = '已完成';
                    }

                    if($value['type']==1){
                        $value['jifen'] = $value['order_jifen'];
                        $value['jifen_price'] = 0;
                        $value['type'] = '积分商城订单';
                    }
                    else{
                        $value['type'] = '商城订单';
                    }


                    // $value['nickname'] = Db::name('user')->where('id',$value['uid'])->value('nickname');

                    // 判断订单属于什么类型
                    if($value['pay_status']==0){
                        //待支付
                        $value['order_status'] = '待支付';
                    }
                    // 用户申请过退款
                    elseif($value['is_refund']==1){
                        if($value['refund_status']==1){
                            $value['order_status'] = '已完成退款';//已完成退款
                        }
                        else{
                            if($value['sure_return']==0){
                                $value['order_status'] = '退款审核中';//买家已申请退款，退款审核中
                            }
                            elseif($value['sure_return']==-1){
                                $value['order_status'] = '拒绝退货';//卖家拒绝退货
                            }
                            else{
                                $value['order_status'] = '同意退货';//卖家同意退货，用户可以上传快递信息
                            }
                        }
                    }
                    elseif($value['is_send']==0){
                        $value['order_status'] = '待发货';//待发货
                    }
                    elseif($value['is_send']==1&&$value['is_que']==0){
                        $value['order_status'] = '待收货';//待收货
                    }
                    else{
                        $value['order_status'] = '已完成';//已完成
                    }

                    $pihao_list = Db::name('product_pihao')->column('id,pihao');
                    if($value['pihao']){
                        $pihao_id_arr = explode(',',$value['pihao']);
                        // $pihao_num_arr = explode(',',$value['pihao_num']);
                        $pihao = array();
                        foreach($pihao_id_arr as $k=>&$v){
                            $pihao[] = $pihao_list[$v];
                        }
                        $value['pihao'] = implode(',',$pihao);
                    }

                    if($value['fp_title']&&$value['fp_type']){
                        if($value['fp_type']==0){
                            $value['fp_type'] = '单位';
                        }
                        elseif($value['fp_type']==1){
                            $value['fp_type'] = '个人';
                        }
                        elseif($value['fp_type']==2){
                            $value['fp_type'] = '专票';
                        }
                    }
                }
            }


            $data['data'] = $list;
            $data['count'] = Db::name('orders')->alias('a')->join('user b','a.uid=b.id','left')->where($where)->count('a.id');
            $data['code'] = 0;
            
            return json($data);

        }
        return $this->fetch();
    }

    function index1(){
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 0);
            $limit      = $this->request->param('limit/d', 0);
            $keyword = input('keyword');
            if($keyword){
                $where[] = ['a.orders_id|a.name|b.nickname','like',"%".$keyword."%"];
                // $where[] = ['name','like',"%".$keyword."%"];
            }
            $bg_time = input('bg_time');
            if($bg_time){
                $bg_time = strtotime($bg_time);
                $where[] = ['a.ctime','gt',$bg_time];
            }
           
            $ed_time = input('ed_time');
            if($ed_time){
                $ed_time = strtotime($ed_time);
                $where[] = ['a.ctime','lt',$ed_time];
            }

            $status = input('status');
            if($status){
                // 待支付
                if($status==1){
                    $where[] = ['a.pay_status','eq',0];
                }
                // 待发货
                elseif($status==2){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_send','eq',0];
                    $where[] = ['a.sure_return','neq',1];
                }
                // 待收货
                elseif($status==3){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_send','eq',1];
                    $where[] = ['a.is_que','eq',0];
                }
                // 退换货
                elseif($status==5){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_refund','eq',1];
                }
                // 已完成
                elseif($status==4){
                    $where[] = ['a.pay_status','eq',1];
                    $where[] = ['a.is_send','eq',1];
                    $where[] = ['a.is_que','eq',1];
                    $where[] = ['a.sure_return','neq',1];
                }
                // 积分商城订单
                elseif($status==6){
                    $where[] = ['a.type','eq',1];
                } 
                // 申请开票订单
                elseif($status==7){
                    $where[] = ['a.fp_title','neq',''];
                    $where[] = ['a.taxNumber','neq',''];
                    $where[] = ['a.is_piao','eq',0];
                } 
                // 已开票订单
                elseif($status==8){
                    $where[] = ['a.is_piao','eq',1];
                } 
            }
            if($page&&$limit){
                $list = Db::name('orders')->alias('a')->join('user b','a.uid=b.id','left')->where($where)->page($page)->limit($limit)->order('a.is_send asc,a.ctime desc')->field('a.*,b.nickname')->select();
            }
            else{
                $list = Db::name('orders')->alias('a')->join('user b','a.uid=b.id','left')->where($where)->order('a.ctime desc')->field('a.*,b.nickname')->select();
            }
            if($list){
                foreach($list as $key=>&$value){
                    $goods_id_arr = explode(',',$value['goods_id']);
                    $goods_spec_arr = explode(',',$value['goods_spec']);
                    $goods_price_arr = explode(',',$value['goods_price']);
                    $goods_num_arr = explode(',',$value['goods_num']);
                    $i = 0;
                    $goods_name = array();
                    foreach($goods_id_arr as $k=>&$v){
                        $ginfo = Db::name('product')->where('id',$v)->field('name,share_img')->find();
                        $goods_info[$i] = array(
                            'id'=>$v,
                            'goods_spec'=>$goods_spec_arr[$k],
                            'goods_num'=>$goods_num_arr[$k],
                            'goods_price'=>$goods_price_arr[$k],
                            'goods_name'=>$ginfo['name'],
                            'goods_img'=>$ginfo['share_img']
                        );
                        $goods_name[$i] = $ginfo['name'];
                        $i++;
                    }
                    $value['output_goods_name'] = implode(',',$goods_name);
                    $value['goods_info'] = $goods_info;

                    $value['ctime'] = $value['ctime']?date('Y-m-d H:i:s',$value['ctime']):'';
                    $value['pay_time'] = $value['pay_time']?date('Y-m-d H:i:s',$value['pay_time']):'';

                    if($value['quan_id']>0){
                        $quan_id = Db::name('user_quan')->where('id',$value['quan_id'])->value('quan_id');
                        $quan_name = Db::name('product_quan')->where('id',$quan_id)->value('quan_name');
                        $value['quan_name'] = $quan_name?$quan_name:'';
                        $value['quan_price'] = $value['quan_price']?$value['quan_price']:0;
                    }

                    if($value['pay_status']==0){
                        $value['status'] = '待支付';
                    }
                    elseif($value['pay_status']==1&&$value['is_send']==0){
                        $value['status'] = '待发货';
                    }
                    elseif($value['pay_status']==1&&$value['is_send']==1&&$value['is_que']==0){
                        $value['status'] = '待收货';
                    }
                    elseif($value['pay_status']==1&&$value['is_send']==1&&$value['is_que']==1){
                        $value['status'] = '已完成';
                    }

                    if($value['type']==1){
                        $value['jifen'] = $value['order_jifen'];
                        $value['jifen_price'] = 0;
                        $value['type'] = '积分商城订单';
                    }
                    else{
                        $value['type'] = '商城订单';
                    }


                    // 判断订单属于什么类型
                    if($value['pay_status']==0){
                        //待支付
                        $value['order_status'] = '待支付';
                    }
                    // 用户申请过退款
                    elseif($value['is_refund']==1){
                        if($value['refund_status']==1){
                            $value['order_status'] = '已完成退款';//已完成退款
                        }
                        else{
                            if($value['sure_return']==0){
                                $value['order_status'] = '退款审核中';//买家已申请退款，退款审核中
                            }
                            elseif($value['sure_return']==-1){
                                $value['order_status'] = '拒绝退货';//卖家拒绝退货
                            }
                            else{
                                $value['order_status'] = '同意退货';//卖家同意退货，用户可以上传快递信息
                            }
                        }
                    }
                    elseif($value['is_send']==0){
                        $value['order_status'] = '待发货';//待发货
                    }
                    elseif($value['is_send']==1&&$value['is_que']==0){
                        $value['order_status'] = '待收货';//待收货
                    }
                    else{
                        $value['order_status'] = '已完成';//已完成
                    }

                    $value['taxNumber'] .= "\t";
                    $value['bankAccount'] .= "\t";
                    $value['waybill_id'] .= "\t";
                    $value['phone'] .= "\t";
                    $value['orders_id'] .= "\t";

                    $pihao_list = Db::name('product_pihao')->column('id,pihao');
                    if($value['pihao']){
                        $pihao_id_arr = explode(',',$value['pihao']);
                        // $pihao_num_arr = explode(',',$value['pihao_num']);
                        $pihao = array();
                        foreach($pihao_id_arr as $k=>&$v){
                            $pihao[] = $pihao_list[$v];
                        }
                        $value['pihao'] = implode(',',$pihao);
                    }

                    if($value['fp_title']&&$value['fp_type']){
                        if($value['fp_type']==0){
                            $value['fp_type'] = '单位';
                        }
                        elseif($value['fp_type']==1){
                            $value['fp_type'] = '个人';
                        }
                        elseif($value['fp_type']==2){
                            $value['fp_type'] = '专票';
                        }
                    }
                }
            }

            // var_dump($list);exit;
            $data['data'] = $list;
            $data['count'] = Db::name('orders')->alias('a')->join('user b','a.uid=b.id','left')->where($where)->count('a.id');
            // var_dump($data['count']);exit;
            $data['code'] = 0;
            
            return json($data);

        }
        return $this->fetch();
    }
    public function sendGoods(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            $id = $list['id'];

            $order_info = Db::name('orders')->where('id',$id)->find();

            // if(!$list['order_sell_num']){
            //     return $this->error('请填写订单价格');
            // }

            if($list['pihao']){
                // Db::name('orders')->where('id',$order_info['id'])->update(array('pihao'=>$list['pihao'],'pihao_num'=>$list['pihao_num']));
                foreach($list['pihao']['name'] as $key=>$value){
                    Db::name('product_pihao')->where('pihao',$value)->setDec('num',$list['pihao']['num'][$key]);
                    Db::name('product_pihao')->where('pihao',$value)->setInc('user_num',$list['pihao']['num'][$key]);
                }
                $pihao = implode(',',$list['pihao']['name']);
                $pihao_num = implode(',',$list['pihao']['num']);
            }
            else{
                return $this->error('请上传批号信息');
            }

            Db::name('orders')->where('id',$order_info['id'])->update(array('pihao'=>$pihao,'pihao_num'=>$pihao_num,'package_num'=>$list['count'],'weight'=>$list['weight']));
            
            $openid = Db::name('user')->where('id',$order_info['uid'])->value('openid');

            $seller_id = $list['seller_id'];
            $seller_info = Db::name('company_info')->where('id',$seller_id)->find();
            if(!$seller_info){
                return $this->error('请选择卖家物流信息模板');
            }

            $goods_id = $order_info['goods_id'];
            $goods_num = $order_info['goods_num'];
            $goods_id_arr = explode(',',$goods_id);
            $goods_num_arr = explode(',',$goods_num);
            $all_goods_num = 0;
            $detail_list = array();
            foreach($goods_id_arr as $k=>$v){
                $name = Db::name('product')->where('id',$v)->value('name');
                $detail_list[] = array('name'=>$name,'count'=>$goods_num_arr[$k]);
                $all_goods_num += $goods_num_arr[$k];
            }

            $shop =array();
            // 只购买了单件商品
            if(count($goods_id_arr)==1){
                $goods_info = Db::name('product')->where('id',$goods_id)->find();
                $shop = array(
                    'wxa_path'=>'/pages/order/order?tab=3',//商家小程序的路径，建议为订单页面
                    'img_url'=>'https://hsq.jiwalgt.com'.$goods_info['share_img'],//商品缩略图 url；shop.detail_list为空则必传，shop.detail_list非空可不传。
                    'goods_name'=>$goods_info['name'],//商品名称, 不超过128字节；shop.detail_list为空则必传，shop.detail_list非空可不传
                    'goods_count'=>$goods_num,//商品数量；shop.detail_list为空则必传。shop.detail_list非空可不传，默认取shop.detail_list的size
                );
            }
            else{
                $detail_list1 = array();
                foreach($goods_id_arr as $k=>$v){
                    $product = Db::name('product')->where('id',$v)->field('name,sub_name,share_img')->find();
                    $detail_list1[] = array(
                        'goods_name'=>$product['name'],
                        'goods_img_url'=>'https://hsq.jiwalgt.com'.$product['share_img'],
                        'goods_desc'=>$product['sub_name']
                    );
                }

                $shop = array(
                    'wxa_path'=>'/pages/order/order?tab=3',//商家小程序的路径，建议为订单页面
                    'detail_list'=>$detail_list1
                );
            }

            $data = array(
                'add_source'=>0,
                'wx_appid'=>config('APPID'),
                'order_id'=>$order_info['orders_id'],
                'openid'=>$openid,
                'delivery_id'=>$list['delivery_id'],
                // 'delivery_id'=>'TEST',
                'biz_id'=>config('biz_id'),
                // 'biz_id'=>'test_biz_id',
                'custom_remark'=>$list['custom_remark'],
                'sender'=>array(
                    'name'=>$seller_info['name'],
                    'mobile'=>$seller_info['mobile'],
                    'province'=>$seller_info['province'],
                    'city'=>$seller_info['city'],
                    'area'=>$seller_info['area'],
                    'address'=>$seller_info['address'],
                    'company'=>$seller_info['company'],
                ),
                'receiver'=>array(
                    'name'=>$order_info['name'],
                    'mobile'=>$order_info['phone'],
                    'province'=>$order_info['province'],
                    'city'=>$order_info['city'],
                    'area'=>$order_info['district'],
                    'address'=>$order_info['address'],
                ),
                'cargo'=>array(
                    'count'=>$list['count'],//包裹数量
                    'weight'=>$list['weight'],//重量单位是千克(kg)
                    'space_x'=>$list['space_x'],//长度单位厘米(cm)
                    'space_y'=>$list['space_y'],//宽度，单位厘米(cm)
                    'space_z'=>$list['space_z'],//高度，单位厘米(cm)
                    'detail_list'=>$detail_list,
                ),
                // 保价信息
                'shop'=>$shop,
                'insured'=>array(
                    'use_insured'=>0,//是否保价，0 表示不保价，1 表示保价
                    'insured_value'=>0,//保价金额，单位是分，比如: 10000 表示 100 元（注：如果不保价，那保价金额填 0 即可）
                ),
                'service'=>array(
                    'service_type'=>0,//服务类型ID，详见已经支持的快递公司基本信息
                    'service_name'=>'标准快件',//服务名称，详见已经支持的快递公司基本信息
                    // 'service_type'=>1,//服务类型ID，详见已经支持的快递公司基本信息
                    // 'service_name'=>'test_service_name',//服务名称，详见已经支持的快递公司基本信息
                ),
                'expect_time'=>time(),
            );
            // file_put_contents('a1.txt',json_encode($data,JSON_UNESCAPED_UNICODE));
            $access_token = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/express/business/order/add?access_token=".$access_token;
            $rs = juhecurl($url,json_encode($data,JSON_UNESCAPED_UNICODE),true);
            // file_put_contents('a2.txt',$rs);
            $res = json_decode($rs,true);
            if($res['errcode']==0&&$res['errmsg']=='ok'){
                Db::name('orders')->where('id',$order_info['id'])->update(array('waybill_id'=>$res['waybill_id'],'delivery_id'=>$list['delivery_id'],'is_send'=>1,'send_time'=>time(),'waybill_data_key'=>$res['waybill_data'][0]['key'],'waybill_data_value'=>$res['waybill_data'][0]['value']));


                // 发送订阅消息提示用户
                $senddata['touser']=$openid;
                $senddata['template_id']="oi34K6UXqzUTik4JuLB3iE2rmaKq0CyB8IQqkYx_q1g";
                $senddata['page'] = "pages/order/order?tab=3";
                // $senddata['miniprogram_state'] = "developer";//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
                $level = Db::name('config')->where('id',1)->value('level');
                if($level==0){
                    $senddata['miniprogram_state'] = "developer";
                }
                elseif($level==1){
                    $senddata['miniprogram_state'] = "trial";
                }
                else{
                    $senddata['miniprogram_state'] = "formal";
                }

                $senddata['data']=array();
                $senddata['data']['character_string3']=array('value'=>$res['waybill_id']);
                $senddata['data']['thing17']=array('value'=>'商家已发货');
                $senddata['data']['number15']=array('value'=>$all_goods_num);
                $senddata['data']['amount9']=array('value'=>$order_info['order_price']);
                $senddata['data']['character_string7']=array('value'=>$order_info['orders_id']);
                
                $access_token = $this->getAccessToken();
                $rs = $this->curlPost('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token,json_encode($senddata),0);
                file_put_contents('222.txt',$rs);
                return $this->success('发货成功');
            }
            else{
                file_put_contents('wuliu_err.txt',$rs);
                return $this->error($rs);
            }
            
            // var_dump($rs);exit;
        }
        $id = input("id/d");
        $formData = Db::name('orders')->where('id',$id)->find();

        $goods_id_arr = explode(',',$formData['goods_id']);
        $goods_spec_arr = explode(',',$formData['goods_spec']);
        $goods_price_arr = explode(',',$formData['goods_price']);
        $goods_num_arr = explode(',',$formData['goods_num']);
        $i = 0;
        $goods_detail = '';
        foreach($goods_id_arr as $k=>&$v){
            $ginfo = Db::name('product')->where('id',$v)->field('name,share_img')->find();
            $goods_detail .= "产品名：".$ginfo['name']."--规格：".$goods_spec_arr[$k]."--数量：".$goods_num_arr[$k]."<br />";
            $i++;
        }
        $this->assign('goods_detail', $goods_detail);
        $this->assign('formData', $formData);

        // $access_token = $this->getAccessToken();
        // $url = "https://api.weixin.qq.com/cgi-bin/express/business/delivery/getall?access_token=".$access_token;
        // $rs = file_get_contents($url);
        // $wuliu = json_decode($rs,true);
        // $wuliu_list = $wuliu['data'];
        $wuliu_list[] = array(
            'delivery_id'=>'ZTO',
            'delivery_name'=>'中通快递'
        );
        $options = '';
        foreach($wuliu_list as $key=>&$value){
            $options .= "<option value='".$value['delivery_id']."'>".$value['delivery_name']."</option>";
        }
        $this->assign('options', $options);

        // 卖家信息
        $seller_info = Db::name('company_info')->select();
        if(!$seller_info){
            $this->error('请先添加卖家物流信息模板','orders/company_data','',2);
            // $this->redirect('orders/company_data')
        }
        $seller_options = '';
        foreach($seller_info as $kk=>&$vv){
            $seller_options .= "<option value='".$vv['id']."'>".$vv['beizhu']."</option>";
        }
        $this->assign('seller_options', $seller_options);

        $pwhere[] = ['num','gt',0];
        $pihao_list = Db::name('product_pihao')->where($pwhere)->order('id asc')->select();

        $pihao_select = '';
        if($pihao_list){
            foreach($pihao_list as $kkk=>&$vvv){
                $pihao_select .= "<option value='".$vvv['id']."'>".$vvv['name'].'-'.$vvv['pihao']."</option>";
            }
        }
        $this->assign('pihao_select', $pihao_select);

        $template = $this->request->param('template', 'send_goods');
        return $this->fetch($template);
    }

    // 发货通知
    public function sendGoodsAct(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            $data['waybill_id'] = $list['waybill_id'];
            $data['is_send'] = 1;
            if(!$list['id']){
                return $this->error('参数缺失');
            }
            $data['send_time'] = time();
            $rs = Db::name('orders')->where('id',$list['id'])->update($data);
            if($rs){
                return $this->success('操作成功');
            }
            else{
                return $this->error('操作失败，请重试');
            }
        }
        $id = input('id/d');
        // $list = Db::name('product_in_record')->where('pid',$id)->order('ctime desc')->select();
        $this->assign('id',$id);

        $formData = Db::name('orders')->where('id',$id)->field('orders_id,id,waybill_id')->find();
        $this->assign('formData',$formData);
        $template = $this->request->param('template', 'send_goods_act');
        return $this->fetch($template);
    }

    // 修改订单价格
    public function changeOrderPrice(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            $data['order_price'] = $list['order_price'];
            $data['price_change_user_name'] = $list['price_change_user_name'];
            $data['price_change_reason'] = $list['price_change_reason'];
            if(!$list['id']){
                return $this->error('参数缺失');
            }
            $orders_id = Db::name('orders')->where('id',$list['id'])->value('orders_id');
            $data['orders_id'] = $orders_id."_c";
            $rs = Db::name('orders')->where('id',$list['id'])->update($data);
            if($rs){
                return $this->success('操作成功');
            }
            else{
                return $this->error('参数无变化，修改失败');
            }
        }
        $id = input('id/d');
        // $list = Db::name('product_in_record')->where('pid',$id)->order('ctime desc')->select();
        $this->assign('id',$id);

        $formData = Db::name('orders')->where('id',$id)->field('orders_id,order_price,id,price_change_user_name,price_change_reason')->find();
        $this->assign('formData',$formData);
        $template = $this->request->param('template', 'change_orders_money');
        return $this->fetch($template);
    }

    // 修改订单
    public function editOrder(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            $id = $list['id'];
            unset($list['id']);
            if(!$id){
                return $this->error('参数缺失');
            }
            $rs = Db::name('orders')->where('id',$id)->update($list);
            if($rs){
                return $this->success('操作成功');
            }
            else{
                return $this->error('参数无变化，修改失败');
            }
        }
        $id = input('id/d');
        // $list = Db::name('product_in_record')->where('pid',$id)->order('ctime desc')->select();
        $this->assign('id',$id);

        $formData = Db::name('orders')->where('id',$id)->field('id,orders_id,name,phone,province,city,district,address,fp_type,fp_title,taxNumber,companyAddress,telephone,bankName,bankAccount')->find();
        $this->assign('formData',$formData);
        $template = $this->request->param('template', 'edit_orders');
        return $this->fetch($template);
    }
    function getOptions(){
        $pwhere[] = ['num','gt',0];
        $pihao_list = Db::name('product_pihao')->where($pwhere)->order('id asc')->select();

        $pihao_select = '';
        if($pihao_list){
            foreach($pihao_list as $kkk=>&$vvv){
                $pihao_select .= "<option value='".$vvv['id']."'>".$vvv['name'].'-'.$vvv['pihao']."</option>";
            }
        }
        $data['data'] = $pihao_select;
        return json($data);
    }
    //获取
	function getAccessToken(){
        $token_info = Db::name('access_token')->where('id',1)->find();
        if($token_info['access_token']&&time()-$token_info['ctime']<7000){
            return $token_info['access_token'];
        }
        else
        {	
            $appid=config('APPID');
            $appserct=config('APPSECRET');
            if(empty($appid)||empty($appserct)){
                return false;
            }
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appserct}";
            $getjson=file_get_contents($url);
            $getdata=json_decode($getjson,true);
            $rt=$getdata['access_token'];
            $time = time();
            if(!$token_info){
                $rs = Db::name('access_token')->insert(array('access_token'=>$rt,'ctime'=>$time));
            }
            else{
                $up_data['access_token'] = $rt;
                $up_data['ctime'] = $time;
                $rs = Db::name('access_token')->where('id',1)->update($up_data);
            }
            if($rs){
                return $rt;
            }
            else{
                return false;
            }
            
        }
      
    }

    
    function company_data(){
        if ($this->request->isAjax()) {

            $where      = [];

            $list = Db::name('company_info')->select();
            foreach($list as &$value){
                if($value['ctime']){
                    $value['ctime'] = date("Y-m-d H:i:s",$value['ctime']);
                }
                else{
                    $value['ctime'] = '';
                }
            }
            $data['data'] = $list;
            $data['count'] = Db::name('company_info')->where($where)->count('id');
            $data['code'] = 0;
            
            return json($data);

        }
        return $this->fetch();
    }

    function add(){
        if($this->request->isPost()){
            $list = $this->request->post();
            
            $list['ctime'] = time();
            $rs = Db::name("company_info")->insert($list);
            // var_dump($list);
            // return $this->error($rs);
            if($rs){
                return $this->success('添加成功');
            }
            else{
                return $this->error('添加失败，请重试');
            }
        }
        else{
            $template = $this->request->param('template', 'company_form');
            return $this->fetch($template);
        }
    }

    function edit(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            // var_dump($list);exit;
            $list['ctime'] = time();
            if(!$list['id']){
                return $this->error('参数错误');
            }
            else{
                $id = $list['id'];
                unset($list['id']);
                $rs = Db::name("company_info")->where('id',$id)->update($list);
                // var_dump($list);
                // return $this->error($rs);
                if($rs){
                    return $this->success('修改成功');
                }
                else{
                    return $this->error('修改失败，请重试');
                }
            }
        }
        $id = input("id/d");
        $formData = Db::name("company_info")->where("id",$id)->find();
        $this->assign('formData', $formData);
        $template = $this->request->param('template', 'company_form');
        return $this->fetch($template);
    }

    function del(){
        $id = input('id/d');
        $rs = Db::name('company_info')->where('id',$id)->delete();
        if($rs){
            return $this->success('删除成功');
        }
        else{
            return $this->error('删除失败，请重试');
        }
    }
    // 同意退款
    function refund(){
        $id = input('id/d');
        // var_dump($id);exit;
        $order_info = Db::name('orders')->where('id',$id)->find();
        if(!$order_info){
            errMsg('无订单信息');
            // return $this->error('无订单信息');
        }
        if($order_info['is_refund']==0){
            errMsg('用户无申请退款');
            // return $this->error('用户无申请退款');
        }
        if($order_info['refund_status']==1){
            errMsg('已退款给用户，请勿重复操作');
            // return $this->error('已退款给用户，请勿重复操作');
        }

        if($order_info['order_price']>0){
            $param = array(
                'appid'=> config('APPID'),
                'mch_id'=> config('WX_MCH_ID'),
                'nonce_str'=> $this->createNoncestr(),
                'out_refund_no'=> $order_info['orders_id'],
                'transaction_id'=> $order_info['transaction_id'],//微信订单号
                'total_fee'=> intval($order_info['order_price']*100),
                'refund_fee'=> intval($order_info['order_price']*100),
            );
            // file_put_contents('aa.txt',json_encode($param));
            $param['sign'] = $this->getSign($param);
            $xmldata = $this->arrayToXml($param);
            $xmlresult = $this->postXmlSSLCurl($xmldata,'https://api.mch.weixin.qq.com/secapi/pay/refund');
            $result = $this->xmlToArray($xmlresult);
            if($result['return_code']=='SUCCESS'&&$result['return_msg']=='OK'){
                $up_data = array('refund_status'=>1,'refund_time'=>time());
                Db::name('orders')->where('id',$id)->update($up_data);
                $this->rebackRestNum($order_info['orders_id']);
    
                // 发送订阅消息提示用户
                $openid = Db::name('user')->where('id',$order_info['uid'])->value('openid');
                $senddata['touser']=$openid;
                $senddata['template_id']="Eh9Z1-ZKYn-NADFIAYsTGuhRue_OWOhK8aNHTWjUkck";
                $senddata['page'] = "pages/order/order?tab=4";
                // $senddata['miniprogram_state'] = "developer";//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
                $level = Db::name('config')->where('id',1)->value('level');
                if($level==0){
                    $senddata['miniprogram_state'] = "developer";
                }
                elseif($level==1){
                    $senddata['miniprogram_state'] = "trial";
                }
                else{
                    $senddata['miniprogram_state'] = "formal";
                }
    
                $senddata['data']=array();
                $senddata['data']['thing1']=array('value'=>'商家已同意退款');
                $senddata['data']['amount3']=array('value'=>$order_info['order_price']);
                $senddata['data']['date4']=array('value'=>date('Y-m-d H:i:s',time()));
                $senddata['data']['character_string2']=array('value'=>$order_info['orders_id']);
                $senddata['data']['character_string7']=array('value'=>'re_'.$order_info['orders_id']);
    
                $access_token = $this->getAccessToken();
                $rs = $this->curlPost('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token,json_encode($senddata),0);
    
                // 返还积分
                if($order_info['jifen']>0){
                    $jifen_data = array(
                        'uid'=>$order_info['uid'],
                        'orders_id'=>$order_info['orders_id'],
                        'jifen'=>$order_info['jifen'],
                        'ctime'=>time(),
                        'month'=>date('m',time()),
                        'year'=>date('Y',time()),
                        'day'=>date('Y-m-d',time()),
                        'type'=>1,
                        'from_type'=>3
                    );
                    Db::name('user_jifen')->insert($jifen_data);
    
                    Db::name('user')->where('id',$order_info['uid'])->setInc('jifen',$order_info['jifen']);
                }

                // 退款扣除已得积分
                // $jifen_data = Db::name("user_jifen")->where('orders_id',$order_info['orders_id'])->find();
                // if($jifen_data){
                //     $jifen_data = array(
                //         'uid'=>$order_info['uid'],
                //         'orders_id'=>$order_info['orders_id'],
                //         'jifen'=>$jifen_data['jifen'],
                //         'ctime'=>time(),
                //         'month'=>date('m',time()),
                //         'year'=>date('Y',time()),
                //         'day'=>date('Y-m-d',time()),
                //         'type'=>2,
                //         'from_type'=>4
                //     );
                //     Db::name('user_jifen')->insert($jifen_data);
    
                //     Db::name('user')->where('id',$order_info['uid'])->setDec('jifen',$jifen_data['jifen']);
                // }
                
                // 扣除上级获得的积分
                if($order_info['parent_id']){
                    $parent_jf_info = Db::name('user_jifen')->where(array('uid'=>$order_info['parent_id'],'orders_id'=>$order_info['orders_id'],'type'=>1,'from_type'=>1))->find();
                    if($parent_jf_info&&$parent_jf_info['jifen']>0){
                        $kq_jf_data = array(
                            'uid'=>$order_info['parent_id'],
                            'orders_id'=>$order_info['orders_id'],
                            'jifen'=>$parent_jf_info['jifen'],
                            'ctime'=>time(),
                            'month'=>date('m',time()),
                            'year'=>date('Y',time()),
                            'day'=>date('Y-m-d',time()),
                            'type'=>2,
                            'identify'=>1,
                            'from_type'=>4
                        );
                        $rs = Db::name('user_jifen')->insert($kq_jf_data);

                        $res = Db::name('user')->where('id',$order_info['parent_id'])->setDec('jifen',$parent_jf_info['jifen']);
                    }
                }

                // file_put_contents('333.txt',$rs);
                okMsg('退款成功');
                // return $this->success('退款成功');
            }
            else{
                file_put_contents("refund_status.txt",json_encode($result));
                errMsg($result['return_msg']);
                // return $this->error($result['return_msg']);
            }
        }
        else{
            $up_data = array('refund_status'=>1,'refund_time'=>time());
            Db::name('orders')->where('id',$id)->update($up_data);
            $this->rebackRestNum($order_info['orders_id']);

            // 发送订阅消息提示用户
            $openid = Db::name('user')->where('id',$order_info['uid'])->value('openid');
            $senddata['touser']=$openid;
            $senddata['template_id']="Eh9Z1-ZKYn-NADFIAYsTGuhRue_OWOhK8aNHTWjUkck";
            $senddata['page'] = "pages/order/order?tab=4";
            // $senddata['miniprogram_state'] = "developer";//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            $level = Db::name('config')->where('id',1)->value('level');
            if($level==0){
                $senddata['miniprogram_state'] = "developer";
            }
            elseif($level==1){
                $senddata['miniprogram_state'] = "trial";
            }
            else{
                $senddata['miniprogram_state'] = "formal";
            }

            $senddata['data']=array();
            $senddata['data']['thing1']=array('value'=>'商家已同意退款');
            $senddata['data']['amount3']=array('value'=>$order_info['order_price']);
            $senddata['data']['date4']=array('value'=>date('Y-m-d H:i:s',time()));
            $senddata['data']['character_string2']=array('value'=>$order_info['orders_id']);
            $senddata['data']['character_string7']=array('value'=>'re_'.$order_info['orders_id']);

            $access_token = $this->getAccessToken();
            $rs = $this->curlPost('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token,json_encode($senddata),0);
            // 返还积分
            if($order_info['jifen']>0){
                $jifen_data = array(
                    'uid'=>$order_info['uid'],
                    'orders_id'=>$order_info['orders_id'],
                    'jifen'=>$order_info['jifen'],
                    'ctime'=>time(),
                    'month'=>date('m',time()),
                    'year'=>date('Y',time()),
                    'day'=>date('Y-m-d',time()),
                    'type'=>1,
                    'from_type'=>3
                );
                Db::name('user_jifen')->insert($jifen_data);

                Db::name('user')->where('id',$order_info['uid'])->setInc('jifen',$order_info['jifen']);
            }
            
            // 查看订单是否有获得积分，获得积分的话要把积分扣掉
            $jifen_check = Db::name('user_jifen')->where(array('orders_id'=>$order_info['orders_id'],'type'=>1,'uid'=>$order_info['uid']))->find();
            if($jifen_check){
                $jifen_data = array(
                    'uid'=>$order_info['uid'],
                    'orders_id'=>$order_info['orders_id'],
                    'jifen'=>$jifen_check['jifen'],
                    'ctime'=>time(),
                    'month'=>date('m',time()),
                    'year'=>date('Y',time()),
                    'day'=>date('Y-m-d',time()),
                    'type'=>2,
                    'from_type'=>4
                );
                Db::name('user_jifen')->insert($jifen_data);
                Db::name('user')->where('id',$order_info['uid'])->setDec('jifen',$jifen_check['jifen']);
            }

            okMsg('退款成功');
        }
        
        // echo ROOT_PATH;exit;
        // echo realpath('/extend/wxpay/cert/apiclient_cert.pem');exit;
        // var_dump($result);exit;
        // $result = $this->xmlToArray($xmlresult);

    }

    // 取消退款
    function delRefund(){
        $id = input('id/d');
        // var_dump($id);exit;
        $order_info = Db::name('orders')->where('id',$id)->find();
        if(!$order_info){
            errMsg('无订单信息');
            // return $this->error('无订单信息');
        }
        if($order_info['is_refund']==0){
            errMsg('用户无申请退款记录');
            // return $this->error('用户无申请退款');
        }
        if($order_info['refund_status']==1){
            errMsg('已退款给用户，无法取消');
            // return $this->error('已退款给用户，请勿重复操作');
        }

        $up_data = array('is_refund'=>0,'refund_reason'=>'','apply_time'=>0);
        $rs = Db::name('orders')->where('id',$id)->update($up_data);
        if($up_data){
            okMsg('操作成功');
        }
        else{
            errMsg('操作失败，请重试');
        }
        
    }

    // 同意退货
    function sureReturn(){
        $id = input('id/d');
        $type = input('type');
        // var_dump($id);exit;
        $order_info = Db::name('orders')->where('id',$id)->find();
        if(!$order_info){
            errMsg('无订单信息');
            // return $this->error('无订单信息');
        }
        if($order_info['is_refund']==0){
            errMsg('用户无申请退款');
            // return $this->error('用户无申请退款');
        }
        if($order_info['sure_return']!=0){
            errMsg('请勿重复操作');
            // return $this->error('已退款给用户，请勿重复操作');
        }
        $up_data = array(
            'sure_return'=>$type
        );
        $rs = Db::name('orders')->where('id',$id)->update($up_data);
        if($rs){
            okMsg('操作成功');
            // return $this->success('操作成功');
        }
        else{
            errMsg('操作失败，请重试');
        }
    }
    // 根据订单id返回库存
    function rebackRestNum($orders_id){
        $order_info = Db::name('orders')->where('orders_id',$orders_id)->find();
        if(!$order_info){
            return false;
        }

        if($order_info['pay_status']==1&&$order_info['is_que']==1){
            return false;
        }

        $goods_id_arr = explode(',',$order_info['goods_id']);
        $goods_spec_arr = explode(',',$order_info['goods_spec']);
        $goods_num_arr = explode(',',$order_info['goods_num']);
        if($order_info['is_slcg']){
            foreach($goods_id_arr as $k=>&$v){
                $goods_info = Db::name('product')->where('id',$v)->field('slcg_spec,slcg_price,spec,rest_num')->find();
                $buy_num = intval($goods_num_arr[$k]);
                // 采购送礼加库存
                if($goods_spec_arr[$k]==$goods_info['slcg_spec']){
                    Db::name('product')->where('id',$v)->setInc('slcg_rest_num',$buy_num);
                    $sell_money = $goods_info['slcg_price']*$buy_num;
                }
                // 普通产品加库存
                else{
                    $goods_all_spec_arr = explode(',',$goods_info['spec']);
                    $goods_rest_num_arr = explode(',',$goods_info['rest_num']);
                    foreach($goods_all_spec_arr as $kk=>&$vv){
                        if($vv==$goods_spec_arr[$k]){
                            $goods_rest_num_arr[$kk] += $buy_num;
                        }
                    }
                    $p_rest_num_str = implode(',',$goods_rest_num_arr);
                    Db::name('product')->where('id',$v)->update(array('rest_num'=>$p_rest_num_str));
                    // Db::name('product')->where('id',$v)->setInc('rest_num',$buy_num);
                    // $sell_money = $goods_price_arr[$k]*$buy_num;
                }
                // Db::name('product')->where('id',$v)->setDec('buy_count',$buy_num);

                // $sell_in_data = array(
                //     'gid'=>$v,
                //     'sell_num'=>$goods_num_arr[$k],
                //     'sell_money'=>$sell_money,
                //     'ctime'=>time()
                // );
                // Db::name('product_sell_record')->insert($sell_in_data);
            }
        }
        else{
            foreach($goods_id_arr as $k=>&$v){
                $buy_num = intval($goods_num_arr[$k]);
                $goods_info = Db::name('product')->where('id',$v)->field('slcg_spec,slcg_price,spec,rest_num')->find();
                $goods_all_spec_arr = explode(',',$goods_info['spec']);
                $goods_rest_num_arr = explode(',',$goods_info['rest_num']);
                foreach($goods_all_spec_arr as $kk=>&$vv){
                    if($vv==$goods_spec_arr[$k]){
                        $goods_rest_num_arr[$kk] += $buy_num;
                    }
                }
                $p_rest_num_str = implode(',',$goods_rest_num_arr);
                Db::name('product')->where('id',$v)->update(array('rest_num'=>$p_rest_num_str));
                // Db::name('product')->where('id',$v)->setInc('buy_count',$buy_num);
                // $sell_in_data = array(
                //     'gid'=>$v,
                //     'sell_num'=>$goods_num_arr[$k],
                //     'sell_money'=>$goods_price_arr[$k]*$goods_num_arr[$k],
                //     'ctime'=>time()
                // );
                // Db::name('product_sell_record')->insert($sell_in_data);
            }
        }
    }

    /*
    * 对要发送到微信统一下单接口的数据进行签名
    */
    public function getSign($Obj){
        foreach ($Obj as $k => $v){
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String."&key=".config('PKey');
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }
    
    /*
    *排序并格式化参数方法，签名时需要使用
    */
    public function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
 
    /*
    * 生成随机字符串方法
    */
    public function createNoncestr($length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ ) {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    //数组转字符串方法
    public function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    
    public function xmlToArray($xml){
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }
    
    //需要使用证书的请求
    public function postXmlSSLCurl($xml,$url,$second=30)
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch,CURLOPT_HEADER,FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
        //设置证书
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT, ROOT_PATH.'extend/wxpay/cert/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,ROOT_PATH.'extend/wxpay/cert/apiclient_key.pem');
        //post提交方式
        curl_setopt($ch,CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        $data = curl_exec($ch);
        
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
			echo "curl出错，错误码:$error"."<br>"; 
			echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
			curl_close($ch);
            return false;
        }
    }

    function curlPost($url, $data){
		$ch = curl_init();
		$header = array('Content-Type: text/plain');
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		$errorno=curl_errno($ch);
		
		$js=json_decode($tmpInfo,1);
		// echo json_encode($js);exit;
		ob_start();
		var_dump($js);
		var_dump($data);
		file_put_contents('er.txt',ob_get_clean());
		return $js;
		
	}

    function fapiao(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            $id = $list['id'];
            $rs = Db::name('orders')->where('id',$id)->update(array('is_piao'=>1));
            if($rs){
                return $this->success('操作成功');
            }
            else{
                return $this->error('已开票，请勿重复操作');
            }
        }
        $id = input('id/d');
        // $list = Db::name('product_in_record')->where('pid',$id)->order('ctime desc')->select();
        $this->assign('id',$id);

        $formData = Db::name('orders')->where('id',$id)->field('fp_type,fp_title,taxNumber,companyAddress,telephone,bankName,bankAccount,fapiao_pic,fapiao_name,fapiao_address,fapiao_email')->find();
        $this->assign('formData',$formData);
        $template = $this->request->param('template', 'fapiao_form');
        return $this->fetch($template);
    }

    function getList(){
        $id = input('id');
        $list = Db::name('product_in_record')->where('pid',$id)->order('ctime desc')->select();
        if($list){
            foreach($list as &$value){
                $value['ctime'] = $value['ctime']?date('Y-m-d H:i:s',$value['ctime']):'';
            }
        }
        $data['data'] = $list;
        $data['count'] = Db::name('product_in_record')->where('pid',$id)->count('id');
        $data['code'] = 0;
        return json($data);
    }

    function yundan(){
        $id = input('id/d');
        $order_info = Db::name('orders')->where('id',$id)->find();
        if(!$order_info){
            return $this->error('无订单信息');
        }

        if($order_info['print_html']){
            $img = base64_decode($order_info['print_html']);
            echo $img;exit;
        }

        $openid = Db::name('user')->where('id',$order_info['uid'])->value('openid');
        
        $data = array(
            'order_id'=>$order_info['orders_id'],
            'openid'=>$openid,
            'delivery_id'=>$order_info['delivery_id']
        );
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/express/business/order/get?access_token=".$access_token;
        $rs = $this->curlPost($url,json_encode($data),0);
        if($rs['errcode']==0&&$rs['errmsg']=='ok'){
            $up_data['print_html'] = $rs['print_html'];
            Db::name('orders')->where('id',$id)->update($up_data);
            $img = base64_decode($rs['print_html']);
            echo $img;exit;
        }
        else{
            var_dump($rs);
        }
        // if($rs[''])
        // var_dump($data);
        // echo "<br /><br /><br /><br /><br />";
        // var_dump($rs);
        // echo "<br /><br /><br /><br /><br />";

        // $url1 = "https://api.weixin.qq.com/cgi-bin/express/business/quota/get?access_token=".$access_token;
        // $data1 = array(
        //     'delivery_id'=>$order_info['delivery_id'],
        //     'biz_id'=>config('biz_id'),
        // );
        // $rs1 = 
    }

    function goods_export(){

    }

     /**
     * 导出excel
     */
    public function export_excel($title,$setCellStyle,$data,$fileName)
    {
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            $spreadsheet->getActiveSheet()->getStyle($setCellStyle)->getFont()->setBold(true)->setName('Arial')->setSize(10);
            //设置标题栏背景颜色
            $spreadsheet->getActiveSheet()->getStyle($setCellStyle)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('#FF7F50');


            //设置第10行行高为100pt。
            $spreadsheet->getActiveSheet()->getRowDimension('1')->setRowHeight(20);

            //如果需要自动计算列宽，可以这样：
            //$spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);

            //设置默认列宽为15。
            $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);

            //设置水平对齐
            // $styleArray = [
            //     'alignment' => [
            //       'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            //     ],
            //   ];

            // $spreadsheet->getStyle('A1')->applyFromArray($styleArray);

            //设置单元格内容
            $titCol = 'A';
            foreach ($title as $key => $value) {
                //单元格内容写入
                $sheet->setCellValue($titCol . '1', $value);
                $titCol++;
            }
            
            $row = 2; 
            foreach ($data as $item) {
                $dataCol = 'A';
                foreach ($item as $value) {
                    //单元格内容写入
                    $sheet->setCellValue($dataCol . $row, $value);
                    $dataCol++;
                }
                $row++;
            }

            //保存
            $writer = IOFactory::createWriter($spreadsheet, 'Xls');
            
            ob_end_clean();
            
            //输出到浏览器
            header('Content-type: text/html; charset=utf-8');
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename=' . $fileName);
            header('Cache-Control: max-age=0');
            $writer->save('php://output');
    }
}

?>